package com.jsgt.greekfire.common.util

import com.jsgt.greekfire.bean.TimeInfo
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

object TimeUtil {

    fun getTimeInfo(millis: Long): TimeInfo {
        val day = (millis / (1000 * 60 * 60 * 24)).toInt()
        val hour = (millis % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)).toInt()
        val minute = (millis % (1000 * 60 * 60) / (1000 * 60)).toInt()
        val second = (millis % (1000 * 60) / 1000).toInt()
        val decimalFormat = DecimalFormat("00")
        val timeInfo = TimeInfo()
        timeInfo.day = if (validLength(day)) day.toString() else decimalFormat.format(day)
        timeInfo.hour = if (validLength(hour)) hour.toString() else decimalFormat.format(hour)
        timeInfo.minutes =
            if (validLength(minute)) minute.toString() else decimalFormat.format(minute)
        timeInfo.seconds =
            if (validLength(second)) second.toString() else decimalFormat.format(second)
        return timeInfo
    }

    private fun validLength(time: Int): Boolean {
        return time.toString().length >= 2
    }


    /**
     * 时间戳转换成字符窜
     */
    fun time2String(time: Long, pattern: String): String? {
        val d = Date(time)
        val sf = SimpleDateFormat(pattern, Locale.getDefault())
        return sf.format(d)
    }

    /**
     * 将字符串转为时间戳
     */
    fun string2Time(time: String?, pattern: String): Long {
        val sdf = SimpleDateFormat(pattern, Locale.getDefault())
        var date = Date()
        try {
            date = sdf.parse(time)
        } catch (e: ParseException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
        return date.time
    }

    /**
     * 获取当前时间戳
     */
    fun getNow(): Long {
        return System.currentTimeMillis()
    }

    fun dealDateFormat(oldDate: String?): String? {
        var date1: Date? = null
        var df2: DateFormat? = null
        try {
            val df: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
            val date: Date = df.parse(oldDate)
            val df1 =
                SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
            date1 = df1.parse(date.toString())
            df2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return df2?.format(date1)
    }
}